package com.itheima.controller.backend;

import com.itheima.common.constant.MessageConstant;
import com.itheima.common.entity.Result;
import com.itheima.pojo.OrderSetting;
import com.itheima.pojo.OrderSettingEdit;
import com.itheima.service.OrderSettingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;

@RestController
@RequestMapping("/ordersetting")
@Slf4j
public class OrderSettingController {

    @Autowired
    private OrderSettingService orderSettingService;

    /**
     *下载模版
     * @param filename
     * @param response
     * @return
     */
    @GetMapping("/download")
    public String download(@RequestParam String filename, HttpServletResponse response) {

        // ResponseEntity<FileSystemResource>
        /*File file = new File("src/main/java/com/itheima/template/ordersetting_template.xlsx" + filename);
        if (!file.exists()) {
            return ResponseEntity.notFound().build();;
        }

        orderSettingService.download(filename,response);*/

        orderSettingService.download(filename,response);
        return "文件下载";
    }

    @PostMapping("/editNumberByOrderDate")
    public Result editNumberByOrderDate(@RequestBody OrderSettingEdit orderSettingEdit) {

        log.info("编辑预约设置:" + orderSettingEdit);

        orderSettingService.editNumberByOrderDate(orderSettingEdit);

        return new Result(true, MessageConstant.ORDERSETTING_SUCCESS);
    }

    @GetMapping("/getOrderSettingByMonth")
    public Result getOrderSettingByMonth(@RequestParam String date) {

        log.info("获取预约设置数据:{}",date);

        try {
            return new Result(true, MessageConstant.GET_ORDERSETTING_SUCCESS, orderSettingService.getOrderSettingByMonth(date));
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_ORDERSETTING_FAIL);
        }
    }

    @PostMapping("/upload")
    public Result uploadExcelFile(@RequestParam("excelFile") MultipartFile file) {


        try {
            if (file.isEmpty()) {
                Result result = new Result(false, "上传excel文件失败");
            }
            orderSettingService.upload(file);

            return new Result(true, MessageConstant.IMPORT_ORDERSETTING_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "上传excel文件失败");
        }
    }
}
